#!/bin/bash
#auto make install Mysql AB Repliation
#by author jfudu.net wugk
#2015-11-16 change
MYSQL_SOFT="mariadb mariadb-server mariadb-devel mariadb-libs"
NUM=`rpm -qa |grep -i mariadb |wc -l`
INIT="mariadb.service"
CODE=$?

#Mysql To Install 2015
if [ $NUM -ne 0 -a -f /usr/lib/systemd/system/$INIT ];then
	echo -e "\033[32mThis Server Mysql already Install.\033[0m"
	read -p "Please ensure yum remove Mysql Server,YES or NO": INPUT

	if [ $INPUT == "y" -o $INPUT == "yes" ];then
	  	yum remove $MYSQL_SOFT -y ;rm -rf /var/lib/mysql /etc/my.cnf
	 	yum install $MYSQL_SOFT -y
	else
		echo	
	fi
else
	yum remove $MYSQL_SOFT -y ;rm -rf /var/lib/mysql /etc/my.cnf
	yum install $MYSQL_SOFT -y
	if [ $CODE -eq 0 ];then
		echo -e "\033[32mThe Mysql Install Successfully.\033[0m"
	else
		echo -e "\033[32mThe Mysql Install Failed.\033[0m"
		exit 1
	fi
fi


cat >/etc/my.cnf<<EOF
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
symbolic-links=0
log-bin=mysql-bin
server-id = 1
auto_increment_offset=1
auto_increment_increment=2
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
EOF

chown -R mysql.mysql /var/log/
mkdir -p /var/run/mysqld
chown -R mysql.mysql /var/run/mysqld
systemctl restart mariadb.service 
ps -ef |grep mysql

MYSQL_CONFIG(){

#Master Config Mysql
mysql -e "grant  replication  slave  on *.* to  'tongbu'@'%'  identified by  '123456';"
MASTER_FILE=`mysql -e "show master status;"|tail -1|awk '{print $1}'`
MASTER_POS=`mysql -e "show master status;"|tail -1|awk '{print $2}'`

#MASTER_IPADDR=`ifconfig eth0|grep "Bcast"|awk '{print $2}'|cut -d: -f2`
MASTER_IPADDR=$(ifconfig|grep "broadcast"|cut -d" " -f10)

read -p "Please Input Slave IPaddr: " SLAVE_IPADDR

#Slave Config Mysql
ssh -l root $SLAVE_IPADDR "yum remove $MYSQL_SOFT -y ;rm -rf /var/lib/mysql /etc/my.cnf ;yum install $MYSQL_SOFT -y" 
#ssh -l root $SLAVE_IPADDR "$my_config" 
scp -r /etc/my.cnf root@$SLAVE_IPADDR:/etc/
ssh -l root $SLAVE_IPADDR "sed -i 's#server-id = 1#server-id = 2#g' /etc/my.cnf" 
ssh -l root $SLAVE_IPADDR "sed -i '/log-bin=mysql-bin/d' /etc/my.cnf" 

ssh -l root $SLAVE_IPADDR "chown -R mysql.mysql /var/log/"
ssh -l root $SLAVE_IPADDR "mkdir -p /var/run/mysqld"
ssh -l root $SLAVE_IPADDR "chown -R mysql.mysql /var/run/mysqld"

ssh -l root $SLAVE_IPADDR "systemctl restart mariadb.service" 
ssh -l root $SLAVE_IPADDR "mysql -e \"change master to master_host='$MASTER_IPADDR',master_user='tongbu',master_password='123456',master_log_file='$MASTER_FILE',master_log_pos=$MASTER_POS;\""
ssh -l root $SLAVE_IPADDR "mysql -e \"slave start;\"" 
ssh -l root $SLAVE_IPADDR "mysql -e \"show slave status\G;\"" 
}

read -p "Please ensure your Server is Master and you will config mysql Replication?yes or no": INPUT
if [ $INPUT == "y" -o $INPUT == "yes" ];then
	MYSQL_CONFIG
else
	exit 0
fi
